import java.util.*;

import package1.TreeNode;

class Solution2 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        Stack<TreeNode> s = new Stack<>();
        if (root == null)
            return ret;
        q.add(root);
        int height = 0;

        while (!q.isEmpty()) {
            int sz = q.size();
            List<Integer> tmp = new ArrayList<>();
            for (int i = 0; i < sz; i++) {
                TreeNode p = q.poll();
                if(p.left != null) q.add(p.left);
                if(p.right != null) q.add(p.right);
                if (height % 2 == 0) {
                    if(p.left != null) s.add(p.left);
                    if(p.right != null) s.add(p.right);
                    tmp.add(p.val);
                } else {
                    for(int j = 0; j < 2; j++) {
                        if(!s.isEmpty()) {
                            TreeNode pop = s.pop();
                            tmp.add(pop.val);
                        } else {
                            break;
                        }
                    }
                }
            }
            ret.add(tmp);
            height++;
        }
        return ret;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}